package com.dustedpixels.jasmin.unit.impl;

import com.dustedpixels.jasmin.unit.Unit;
import com.dustedpixels.jasmin.unit.implbase.UnitImplBase;

/**
 * A unit combined of two units: master and slave.
 */
public final class DualUnit extends UnitImplBase {
    private final Unit masterUnit;
    private final Unit slaveUnit;
    private int cycleDifference;
    
    public DualUnit(Unit masterUnit, Unit slaveUnit) {
        this.masterUnit = masterUnit;
        this.slaveUnit = slaveUnit;
        this.cycleDifference = 0;
    }
    
    public int processSlice() {
        // Process master slice.
        int masterCyclesProcessed = masterUnit.processSlice();
        
        // Process slice of master unit.
        cycleDifference += masterCyclesProcessed; 
        
        // Let the slave unit catch up master unit.
        if (cycleDifference > 0) {
            cycleDifference -= slaveUnit.processCycles(cycleDifference);
        }
        
        return masterCyclesProcessed;
    }
}
